#include "tools.h"

Operator operator[OPERATOR_MAX];

Book_type_index book_type_index[TYPE_MAX];
Book_key_index book_key_index[KEY_MAX];


int cnt_operator;

char get_cmd(char start,char end)
{
	assert(start <= end);

	puts("-------------------");
	printf("请输入指令：");
	for(;;)
	{
		char cmd = getch();
		if(start <= cmd && cmd <= end)
		{
			printf("%c\n",cmd);
			return cmd;
		}
	}
}

void print_sec(const char* msg,float sec)
{
	printf("\33[01;32m %s \33[00m\n",msg);
	usleep(1000000*sec);
}

void anykey_continue(void)
{
	fflush(stdin);
	puts("按任意键继续...");
	getch();
}

char* get_str(char* str,size_t size)
{
	assert(NULL!=str && size>1);

	// 计算fgets读取了多少个字符
	size_t len = strlen(fgets(str,size,stdin));

	// 如果最后一个字符是'\n'，则把它改为'\0'
	if('\n' == str[len-1])
		str[len-1] = '\0';
	else
		// 如果最后一个字符不是'\n'，则说明缓冲区中有垃圾数据，则需要清理输入缓冲区
		while('\n' != getchar());
	return str;
}

char* get_passwd(char* passwd,size_t size)
{
	int i = 0;
	while(i < size-1)
	{
		passwd[i] = getch();

		// 读取到退格键
		if(127 == passwd[i])
		{
			// 数组中有已输入密码
			if(i > 0)
			{
				// 删除一位密码
				i--;
				printf("\b \b");
			}
			continue;
		}
		if('\n' == passwd[i])
		{
			break;
		}
		
		i++;
		printf("*");
	}
	passwd[i] = '\0';
	printf("\n");
	return passwd;
}

bool yes_or_no(void)
{
	printf("是否确认此操作(y/n)?");
	for(;;)
	{
		char cmd = getch();
		if('y' == cmd || 'Y' == cmd || 'n' == cmd || 'N' == cmd)
		{
			printf("%c\n",cmd);
			return 'y'==cmd || 'Y'==cmd;
		}
	}
}

int query_operatorid(const int id) 		//用操作员ID 查找操作员
{
	for(int i=0; i<cnt_operator; i++)
	{
		if(id == operator[i].id)
			return i;
	}
	return -1;
}

int get_operatorid(void)          		//自动寻找操作员空余ID
{
	for(int i=101;i<151;i++)
	{
		if(-1 == query_operatorid(i))
		{
			return i;
		}
	}
	return -1;
}


//添加学生
void add_stu_node(const char* name,const char* password,const char* path)
{//创建学生文件
	FILE* wfp = fopen(path,"w");
	fprintf(wfp,"姓名:%s 密码:%s\n",name,password);
	fprintf(wfp,"0\n0\n0\n0\n");						//新添加的学生 记录均为0;
	fclose(wfp);
}


//删除
void reduce_operator(int index)					//删除操作员
{
	if(yes_or_no())
		{
			// 把最后一个用户移动给要删除的用户位置
			operator[index] = operator[cnt_operator-1];
			// 后勤人数数量减1
			cnt_operator--;
			print_sec("删除操作员成功！",0.75);
			return;
		}
	print_sec("取消删除操作！",0.75);
}

// 通用的二进制保存数据
int save_data(void* base,size_t size,const char* path)
{
	assert(NULL!=base && 0!=size && NULL!=path);

	FILE* wfp = fopen(path,"w");
	if(NULL == wfp)
	{
		printf("无法打开文件，无法保存数据！\n");
		return 0;
	}

	int ret = fwrite(base,1,size,wfp);
	fclose(wfp);
	return ret;
}

// 通用的二进制加载数据
int load_data(void* base,size_t size,const char* path)
{
	assert(NULL!=base && 0!=size && NULL!=path);

	FILE* rfp = fopen(path,"r");
	if(NULL == rfp)
	{
		printf("无法打开文件，加载数据失败！\n");
		return 0;
	}

	int ret = fread(base,1,size,rfp);
	fclose(rfp);
	return ret;
}

void save_book_index(void)						//保存书籍索引
{
	FILE* wfp = fopen("book_index.txt","w");
	for(int i=0;i<TYPE_MAX;i++)
	{
		fprintf(wfp,"sum:%d cap:%d\n",book_type_index[i].sum,book_type_index[i].cap);
		for(int j=0;j<book_type_index[i].sum;j++)
		{
			fprintf(wfp,"ISBN:%s\n",book_type_index[i].id[j]);
		}
	}
	for(int i=0;i<KEY_MAX;i++)
	{
		fprintf(wfp,"sum:%d cap:%d\n",book_key_index[i].sum,book_key_index[i].cap);
		for(int j=0;j<book_key_index[i].sum;j++)
		{
			fprintf(wfp,"ISBN:%s\n",book_key_index[i].id[j]);
		}
	}
	fclose(wfp);
}

void load_book_index(void)
{
	FILE* rfp = fopen("book_index.txt","r");
	if(NULL == rfp)
	{
		init_book_index();
		return;
	}
	for(int i=0;i<TYPE_MAX;i++)
	{
		fscanf(rfp,"sum:%d cap:%d\n",&book_type_index[i].sum,&book_type_index[i].cap);
		book_type_index[i].id = malloc(book_type_index[i].cap*sizeof(char*));
		for(int j=0;j<book_type_index[i].sum;j++)
		{
			book_type_index[i].id[j] = malloc(14);					//ISBN13位+'\0'
			fscanf(rfp,"ISBN:%s\n",book_type_index[i].id[j]);
		}
	}
	for(int i=0;i<KEY_MAX;i++)
	{
		fscanf(rfp,"sum:%d cap:%d\n",&book_key_index[i].sum,&book_key_index[i].cap);
		book_key_index[i].id = malloc(book_key_index[i].cap*sizeof(char*));
		for(int j=0;j<book_key_index[i].sum;j++)
		{
			book_key_index[i].id[j] = malloc(14);
			fscanf(rfp,"ISBN:%s\n",book_key_index[i].id[j]);
		}
	}
	fclose(rfp);
}

void init_book_index(void)				//初始化索引表
{
	for(int i=0;i<TYPE_MAX;i++)
	{
		book_type_index[i].sum = 0;
		book_type_index[i].cap = 1000;
		book_type_index[i].id = malloc(1000*sizeof(char*));
	}
	for(int i=0;i<KEY_MAX;i++)
	{
		book_key_index[i].sum = 0;
		book_key_index[i].cap = 1000;
		book_key_index[i].id = malloc(1000*sizeof(char*));
	}
}

Student* read_stu(const char* id)
{
    char path[100] = "/home/coco/图书馆管理系统/stu_data/";
    strcat(path,id);
    FILE* rfp = fopen(path,"r");
    if(NULL == rfp)
    {
        print_sec("没有该学号的学生!\n",0.75);
        return NULL;
    }
    char name[20],password[20];
    fscanf(rfp,"姓名:%s 密码:%s\n",name,password);
    Student* stu = create_node_stu(id,name,password);

    fscanf(rfp,"%u\n",&(stu->recond->borrow_sum));
    for(int i=0;i<stu->recond->borrow_sum;i++)
    {
        char data[60];
        fscanf(rfp,"%s\n",data);
		long int time_sec;
		fscanf(rfp,"%ld\n",&time_sec);
        add_node_recond(stu->recond->head_borrow,data,time_sec);
    }
    fscanf(rfp,"%u\n",&(stu->recond->repay_sum));
    for(int i=0;i<stu->recond->repay_sum;i++)
    {
        char data[60];
        fscanf(rfp,"%s\n",data);
		long int time_sec;
		fscanf(rfp,"%ld\n",&time_sec);
        add_node_recond(stu->recond->head_repay,data,time_sec);
    }
    fscanf(rfp,"%u\n",&(stu->recond->order_sum));
    for(int i=0;i<stu->recond->order_sum;i++)
    {
        char data[60];
        fscanf(rfp,"%s\n",data);
		long int time_sec;
		fscanf(rfp,"%ld\n",&time_sec);
        add_node_recond(stu->recond->head_order,data,time_sec);
    }
    fscanf(rfp,"%u\n",&(stu->recond->overdue_sum));
    for(int i=0;i<stu->recond->overdue_sum;i++)
    {
        char data[60];
        fscanf(rfp,"%s\n",data);
		long int time_sec;
		fscanf(rfp,"%ld\n",&time_sec);
        add_node_recond(stu->recond->head_overdue,data,time_sec);
    }
    return stu;
}

void write_stu(Student* stu)
{
    char path[100] = "/home/coco/图书馆管理系统/stu_data/";
    strcat(path,stu->id);
    FILE* wfp = fopen(path,"w");
    fprintf(wfp,"姓名:%s 密码:%s\n",stu->name,stu->password);

    fprintf(wfp,"%u\n",stu->recond->borrow_sum);
    Recond_node* tmp = stu->recond->head_borrow->next;
    for(int i=0;i<stu->recond->borrow_sum;i++)
    {
        fprintf(wfp,"%s\n",tmp->data);
		fprintf(wfp,"%ld\n",tmp->time_sec);
        tmp = tmp->next;
    }

    fprintf(wfp,"%u\n",stu->recond->repay_sum);
    tmp = stu->recond->head_repay->next;
    for(int i=0;i<stu->recond->repay_sum;i++)
    {
        fprintf(wfp,"%s\n",tmp->data);
		fprintf(wfp,"%ld\n",tmp->time_sec);
        tmp = tmp->next;
    }

    fprintf(wfp,"%u\n",stu->recond->order_sum);
    tmp = stu->recond->head_order->next;
    for(int i=0;i<stu->recond->order_sum;i++)
    {
        fprintf(wfp,"%s\n",tmp->data);
		fprintf(wfp,"%ld\n",tmp->time_sec);
        tmp = tmp->next;
    }

    fprintf(wfp,"%u\n",stu->recond->overdue_sum);
    tmp = stu->recond->head_overdue->next;
    for(int i=0;i<stu->recond->overdue_sum;i++)
    {
        fprintf(wfp,"%s\n",tmp->data);
		fprintf(wfp,"%ld\n",tmp->time_sec);
        tmp = tmp->next;
    }
    fclose(wfp);
}

void write_book_msg(Book* book)
{
    char path[100] = "/home/coco/图书馆管理系统/book_data/";
    strcat(path,book->ISBN);
    FILE* wfp = fopen(path,"w");
    fprintf(wfp,"书名:%s 作者:%s 出版社:%s\n",book->bookname,book->writer,book->publish);
    fprintf(wfp,"总数:%u 价格%.2f 类型:%u 首字母:%u\n",book->book_sum,book->book_price,book->type,book->key);
    fprintf(wfp,"出借:%u 预约:%u 自然损坏:%u 人为损坏:%u",book->book_borrowed,book->book_ordered,book->broken_aging,book->broken_manmade);
    fclose(wfp);
}

Book* read_book_msg(const char* ISBN)
{
    char path[100] = "/home/coco/图书馆管理系统/book_data/";
    strcat(path,ISBN);
    FILE* rfp = fopen(path,"r");
    if(NULL == rfp)
    {
        printf("没有该书籍!\n");
        return NULL;
    }
    Book* book = malloc(sizeof(Book));
    strcpy(book->ISBN,ISBN);
    fscanf(rfp,"书名:%s 作者:%s 出版社:%s\n",book->bookname,book->writer,book->publish);
    fscanf(rfp,"总数:%u 价格%f 类型:%u 首字母:%u\n",&(book->book_sum),&(book->book_price),&(book->type),&(book->key));
    fscanf(rfp,"出借:%u 预约:%u 自然损坏:%u 人为损坏:%u",&(book->book_borrowed),&(book->book_ordered),&(book->broken_aging),&(book->broken_manmade));
    fclose(rfp);
    return book;
}

void show_time_msg(long int time_sec)
{
	char YMD[15] = {0};
    char HMS[10] = {0};
    char *cur_time = (char *)malloc(21*sizeof(char));
   	struct tm* now_time;

    now_time = localtime(&time_sec);

    strftime(YMD, sizeof(YMD), "%F ", now_time);
    strftime(HMS, sizeof(HMS), "%T", now_time);

    strcpy(cur_time, YMD);
    strncat(cur_time, HMS, 8);
	printf("%s\n",cur_time);
}